<?php

namespace addons\qingdongams\model;

use think\Exception;
use think\Model;
use traits\model\SoftDelete;

/**
 *日程提醒
 */
class Event Extends Model {
	use SoftDelete;
	const   CUSTOMER_TYPE    = 1;//客户
	const   CONTACTS_TYPE    = 2;//联系人
	const   CONTRACT_TYPE    = 3;//订单
	const   LEADS_TYPE       = 4;//线索
	const   RECEIVABLES_TYPE = 5;//回款记录

    protected $name = 'qingdongams_event';
	// 开启自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';
	protected $deleteTime = 'deletetime';
    protected $append = [
        'show_staff_data',
    ];

    protected static function init()
    {
        self::beforeUpdate(function ($model) {
            if(isset($model->status)){
                if ($model->status == 2) {
                    $model->actual_end_time=time();
                }
            }
        });
    }

    public function getShowStaffDataAttr($value,$data)
    {
        if (!isset($data['show_staff_ids'])) {
            return '';
        }
        $ids=explode(',',$data['show_staff_ids']);
        return Staff::where(['id'=>['in',$ids]])->field('id,name,img,post,mobile')->select();
    }

    //评论
    public function comments()
    {
        return $this->hasMany(Comment::class, 'relation_id', 'id')->where(['relation_type'=>'assist_event'])->with('staff')->field('id,relation_id,content,staff_id,file_ids,createtime');
    }


    public function getCreatetimeAttr($value) {
        return date('Y-m-d H:i:s', $value);
    }



	//获取紧要程度
	public static function getLevel($level) {
		$levels = [0 => '普通', 1 => '重要', 2 => '紧急', 4 => '重要且紧急'];

		return $levels[$level] ?? "普通";
	}


	//获取日程状态
	public static function getStatus($status) {
		$statuss = [0 => '未开始', 1 => '进行中', 2 => '已结束', 3 => '任务终止'];

		return $statuss[$status] ?? "未开始";
	}


	//创建日程
    public static function createEvent($params)
    {
        $staff = Staff::info();
        if (isset($params['event_type'])) {
            if(isset($params['event_type'][2]) && in_array($params['event_type'][2],['上门安装','上门维修']) ){
                if($params['event_type'][1] != '上门'){
                    unset($params['event_type'][2]);
                }
            }
            $params['event_type'] = implode('_', $params['event_type']);
            $params['customer_id'] = $params['relation_id'];
            $params['event_type'] = trim($params['event_type'], '_');
        }
        if (empty($params['staff_id'])) {
            $params['staff_id'] = $staff->id;
        }
        $params['create_staff_id'] = $staff->id;
        $params['show_staff_ids'] = $params['staff_id'];
        if (empty($params['relation_type'])) {
            $params['relation_type'] = StaffSignIn::EVENT_TYPE;
        }
        if (isset($params['event_type'])) {
            $params['owner_staff_id'] = $params['staff_id'];

            if ($params['event_type'] == '设计工单') {

                $workorderModel = new Workorder();
                $content = '创建设计工单';
                $params['workorder_type'] = '设计工单';
                $params['workorder_number'] = 'S' . date('ymd') . rand(100, 999);
                $workorderLastid = $workorderModel::createWorkorder($params);
                $signin['relation_type'] = StaffSignIn::WORKORDER_TYPE;
                $signin['relation_id'] = $workorderLastid;
                //创建跟进记录
                StaffSignIn::quickSignIn($params['customer_id'], $content, $signin);

                $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
                $params['relation_id'] = $workorderLastid;
            } else if ($params['event_type'] == '售后服务_返厂维修') {
                $workorderModel = new Workorder();

                $content = '创建售后服务-返厂维修';
                $params['workorder_type'] = '返厂维修';
                $params['workorder_number'] = 'S' . date('ymd') . rand(100, 999);
                $workorderLastid = $workorderModel::createWorkorder($params);
                $signin['relation_type'] = StaffSignIn::WORKORDER_TYPE;
                $signin['relation_id'] = $workorderLastid;
                //创建跟进记录
                StaffSignIn::quickSignIn($params['customer_id'], $content, $signin);

                $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
                $params['relation_id'] = $workorderLastid;
            } else if ($params['event_type'] == '售后服务_上门_上门安装') {
                $workorderModel = new Workorder();

                $content = '创建服务-上门安装';
                $params['workorder_type'] = '上门安装';
                $params['workorder_number'] = 'S' . date('ymd') . rand(100, 999);
                $workorderLastid = $workorderModel::createWorkorder($params);
                $signin['relation_type'] = StaffSignIn::WORKORDER_TYPE;
                $signin['relation_id'] = $workorderLastid;
                //创建跟进记录
                StaffSignIn::quickSignIn($params['customer_id'], $content, $signin);

                $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
                $params['relation_id'] = $workorderLastid;
            } else if ($params['event_type'] == '售后服务_上门_上门维修') {
                $workorderModel = new Workorder();

                $content = '创建服务-上门维修';
                $params['workorder_type'] = '上门维修';
                $params['workorder_number'] = 'S' . date('ymd') . rand(100, 999);
                $workorderLastid = $workorderModel::createWorkorder($params);
                $signin['relation_type'] = StaffSignIn::WORKORDER_TYPE;
                $signin['relation_id'] = $workorderLastid;
                //创建跟进记录
                StaffSignIn::quickSignIn($params['customer_id'], $content, $signin);

                $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
                $params['relation_id'] = $workorderLastid;
            }
        }
        if (isset($params['product_part'])) {
            unset($params['product_part']);
        }
        $Model = new self;
        // 调用当前模型对应的User验证器类进行数据验证
        $result = $Model->allowField(true)->save($params);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception($Model->getError());
        }
        $lastId = $Model->getLastInsID();
//        JointFollow::initJointFollow( JointFollow::EVENT_TYPE,$lastId,$params['staff_id'],$params['show_staff_ids']);
        $data = [
            'staff_id' => $staff->id,
            'customer_id' => $params['customer_id']??0,//客户id
            'relation_process' => '创建任务',//日程类型
            'relation_type' => StaffSignIn::EVENT_TYPE,//日程类型
            'relation_id' => $lastId,//签到关联id
            'content' => '创建任务',
        ];
        StaffSignIn::createSignIn($data);
        if (isset($params['type']) && $params['type'] == 4) {//任务
            $staff = Staff::info();
            //发送通知
            Message::addMessage(Message::ASSIST_EVENT_TYPE, $lastId, $params['staff_id'], $staff->id,
                $staff->name . '邀请您协助工作，请您及时查看');
        } else {
            $staff = Staff::info();
            if ($params['staff_id'] != $staff->id &&  $params['relation_type'] == StaffSignIn::EVENT_TYPE) {
                //发送通知
                Message::addMessage(Message::EVENT_TYPE, $lastId, $params['staff_id'], $staff->id,
                    $staff->name . '指派给您一项任务，请您及时审阅');
            }
        }
        return true;
    }

    //修改日程信息
    public static function editEvent($params)
    {
        $staff = Staff::info();
        $params['status'] = 0;
        $row=self::get($params['id']);
        if(empty($params['staff_id']) ){
            $params['staff_id'] = $staff->id;
            //发送通知
            Message::addMessage(Message::WORKORDER_TYPE, $row->id,
                $params['staff_id'], $staff->id,
                $staff->name.'《'.$row->title.'》指派给您一件任务，请您及时审阅');
        }

        $Model              = new self;
        // 调用当前模型对应的User验证器类进行数据验证
        $result = $Model->allowField(true)->save($params,['id'=>$params['id']]);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception($Model->getError());
        }

        return true;
    }

	/**
	 *变更状态
	 */
	public static function changeStatus($id, $status) {
		$model = new self();
		if ($model->save(['status' => $status], ['id' => $id]) == false) {
			throw new Exception('变更失败');
		}

		return true;
	}


	//根据时间获取列表
	public static function getTimeList($start_time, $end_time) {
		$staff      = Staff::info();
		$model      = new self();
		$start_time = $start_time . ' 00:00:00';
		$end_time   = $end_time . ' 23:59:59';
		$events     = $model->where([
			'staff_id' => $staff->id,
		])->where(function ($query) use ($start_time, $end_time) {
			$query->where(['start_time' => ['between', [$start_time, $end_time]]])->whereOr([
				'end_time' => [
					'between',
					[
						$start_time,
						$end_time
					]
				]
			]);
		})->select();
		$data       = [];
		$start_time = strtotime($start_time);
		$end_time   = strtotime($end_time);
		for ($start_time; $start_time <= $end_time; $start_time = strtotime('+1 day', $start_time)) {
			$time        = date('Y-m-d', $start_time);
			$data[$time] = [];
			foreach ($events as $k => $v) {
				if (strtotime($v['start_time']) <= $start_time + 86400 - 1 && strtotime($v['end_time']) >= $start_time) {
					$data[$time][] = $v;
				}
			}
		}
		foreach ($data as &$times) {
			foreach ($times as &$ves) {
				$ves['start_time'] = date('Y-m-d H:i', strtotime($ves['start_time']));
				$ves['end_time']   = date('Y-m-d H:i', strtotime($ves['end_time']));
			}
		}

		return $data;
	}


	/**
     * 修改任务状态
	 * @desc 备注
	 * @update_date 2021/7/16 更新时间
	 * @author zhangwei
	 */
	public static function updateProcess($id, $process,$last_event='') {
        $staff=Staff::info();
		$model = new self;
		$save  = ['process' => $process];
        $row=$model::get($id);

		if ($process == 1) {//开始
			$save['status'] = 1;
			$save['actual_start_time'] = time();
            if($row['event_type'] == '客户服务_电话' || $row['event_type'] == '客户服务_微信' || $row['event_type'] == '售后服务_电话'){
                $save['process'] = 2;
            }

		}
		if ($process == 2) {//到访时间
			$save['actual_arrive_time'] = time();
		}
		if ($process == 3) {//完成
		    if(empty($row)){
                throw new Exception('日程不存在');
            }
            $save['last_event']=$last_event;
            if($last_event != '返程'){//如果是拜访下一家 则任务结束
                $save['status'] = 2;
            }
			$save['actual_end_time'] = time();//结束时间
            //日程工作时长
			$use_time= $save['actual_end_time'] -$row->actual_start_time;
            $save['use_time'] = intval(($use_time%3600)/60);
			if($row->type == 2){//任务完成
                //发送通知
                Message::addMessage(Message::EVENT_TYPE, $id, $row->create_staff_id, $row->id,$staff->name.'刚刚完成一个任务，指定由您处理');
            }
		}
        if($process == 4){//返程签到
            $save['status'] = 2;
        }
		$result = $model->save($save, ['id' => $id]);
		if ($result == false) {
			// 验证失败 输出错误信息
			throw new Exception($model->getError());
		}

		return true;
	}


	//负责人
	public function staff() {
		return $this->hasOne(Staff::class, 'id', 'staff_id')->field('id,name,img,post,department_id');
	}


	//客户
	public function customer() {
		return $this->hasOne(Customer::class, 'id', 'relation_id')->field('id,name');
	}

	//联系人
	public function contacts() {
		return $this->hasOne(Contacts::class, 'customer_id', 'customer_id')->field('id,name,mobile,customer_id,mobilecode,region');
	}

}
